package cn.hou.optional;

import java.util.Optional;

import org.junit.Test;

import cn.hou.java8.Employee;

//Optional容器类
public class TestOptional {
	
	//创建Optional实例
	@Test
	public void test01(){
		//创建Optional实例
		Optional<Employee> of = Optional.of(new Employee());
		System.out.println(of.get());
		//创建一个空的实例,不能get()
		Optional<Object> empty = Optional.empty();
		// 参数不为null,返回参数,否则返回空实例
		Optional<Employee> ofNullable = Optional.ofNullable(new Employee());
		System.out.println(ofNullable.get());
	}
	@Test
	public void test02(){
		Optional<Employee> of = Optional.of(new Employee());
		if(of.isPresent()){ //判断是否有值
			System.out.println(of.get());
		}
		//如果of包含值,返回该值,否则返回参数值
		of.orElse(new Employee());
		of.orElseGet(Employee::new);//返回lambda返回的值
		Optional<String> map = of.map(x->x.getName());
		System.out.println(map);//Optional.empty
		//必须返回Optinal实例
		of.flatMap(x->Optional.of(x.getAge()));
	}
	@Test
	public void test03(){
		Optional<Man> ofNullable2 = Optional.ofNullable(new Man());
		String goddessName = getGoddessName(ofNullable2);
		System.out.println(goddessName);
	}
	//获取男人心中的女神
	public String getGoddessName(Optional<Man> man){
		return  man.orElse(new Man()) //如果为空,返回一个man空实例
				.getGoddess()   //为空返回Optional.empty空实例
				.orElse(new Goddess("杨幂")) //为空赋默认值
				.getName();
	}

}
